/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"

#include "esp_log.h"
#include "mqtt_client.h"
#include <unistd.h>

#include <hmi.h>
#include <rtk.h>

#include "dwm_api.h"
#include "uwb.h"
#include "console.h"
#include "wifi_sta.h"
#include "key.h"







//OTA
#include "user_mqtt.h"
#include "aliyun_ota.h"
#include "cJSON.h"

//OTA

static const char *TAG = "FHPL_ESP32_DEMO";

#define TIME_ZONE (+8)   //Beijing Time
#define YEAR_BASE (2000) //date in GPS starts from 2000

esp_mqtt_client_handle_t client;

rtk_handle_t rtk_hdl;
uwb_handle_t uwb_hdl;
#define TOPIC_LEN_MAX	128
static char pub_topic_status[TOPIC_LEN_MAX]="";
static char pub_topic_nmea[TOPIC_LEN_MAX]="";
static char pub_topic_rtk_location[TOPIC_LEN_MAX]="";
static char pub_topic_uwb_location[TOPIC_LEN_MAX]="";
char pub_topic_key[TOPIC_LEN_MAX]="";
static char sub_topic_voice[TOPIC_LEN_MAX]="";
static char sub_topic_beep[TOPIC_LEN_MAX]="";
static char sub_topic_light[TOPIC_LEN_MAX]="";

static void topic_fill_device_id(void)
{
    //获取nodeid
    uint64_t nodeid;
    dwm_init();
    assert(RV_OK == dwm_node_id_get(&nodeid));
    dwm_deinit();
    nodeid &= 0xffff;
    ESP_LOGI(TAG,"Node ID:%04x",(uint16_t)nodeid);
	//设备端发布Topic
	snprintf(pub_topic_status,TOPIC_LEN_MAX,"status/%04x",(uint16_t)nodeid);
	snprintf(pub_topic_nmea,TOPIC_LEN_MAX,"rtk/%04x/nmea",(uint16_t)nodeid);
	snprintf(pub_topic_rtk_location,TOPIC_LEN_MAX,"rtk/%04x/location",(uint16_t)nodeid);
	snprintf(pub_topic_uwb_location,TOPIC_LEN_MAX,"uwb/%04x/location",(uint16_t)nodeid);
	snprintf(pub_topic_key,TOPIC_LEN_MAX,"key/%04x",(uint16_t)nodeid);
	//设备端订阅Topic
	snprintf(sub_topic_voice,TOPIC_LEN_MAX,"alarm/%04x/voice",(uint16_t)nodeid);
	snprintf(sub_topic_beep,TOPIC_LEN_MAX,"alarm/%04x/beep",(uint16_t)nodeid);
	snprintf(sub_topic_light,TOPIC_LEN_MAX,"alarm/%04x/light",(uint16_t)nodeid);
}

static void log_error_if_nonzero(const char * message, int error_code)
{
    if (error_code != 0) {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}
static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    char string[20] = { 0 };


    // your_context_t *context = event->context;
    switch (event->event_id) {
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");

            msg_id = esp_mqtt_client_publish(client, pub_topic_status, "online", sizeof("online")-1, 1, 1);
            ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

            msg_id = esp_mqtt_client_subscribe(client, sub_topic_voice, 0);
            ESP_LOGI(TAG, "sent subscribe %s successful, msg_id=%d",sub_topic_voice, msg_id);

            msg_id = esp_mqtt_client_subscribe(client, sub_topic_beep, 0);
            ESP_LOGI(TAG, "sent subscribe %s successful, msg_id=%d",sub_topic_beep, msg_id);

            msg_id = esp_mqtt_client_subscribe(client, sub_topic_light, 0);
            ESP_LOGI(TAG, "sent subscribe %s successful, msg_id=%d",sub_topic_light, msg_id);
        	led_set(2, "000000",0);
            break;
        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        	led_set(2, "ff0000",0);
        	hmi_beep(500,50,2);
            break;
        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_UNSUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_PUBLISHED:
            ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
            break;
        case MQTT_EVENT_DATA:
            ESP_LOGI(TAG, "MQTT_EVENT_DATA");
            printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
            printf("DATA=%.*s\r\n", event->data_len, event->data);

            if(0 == strncmp(event->topic,sub_topic_beep,event->topic_len))
            {
            	if(0 == strncmp(event->data, "on",event->data_len))
            		hmi_beep_on();
            	else if(0 == strncmp(event->data, "off",event->data_len))
            		hmi_beep_off();
            }
            else if(0 == strncmp(event->topic, sub_topic_light, event->topic_len))
            {
				strncpy(string, event->data, event->data_len);
				led_set(3, string,0);
            }
            else if(0 == strncmp(event->topic, sub_topic_voice, event->topic_len))
            {
            	tts_speak(event->data, event->data_len);

            }
            else
            {
            	ESP_LOGI(TAG, "Unknown topic %s",event->topic);
            }

            break;
        case MQTT_EVENT_ERROR:
            ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
            if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT) {
                log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
                log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
                log_error_if_nonzero("captured as transport's socket errno",  event->error_handle->esp_transport_sock_errno);
                ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
            }
            break;
        case MQTT_EVENT_BEFORE_CONNECT:
        	led_set(2, "ffff00",0);
        	break;
        default:
            ESP_LOGI(TAG, "Other event id:%d", event->event_id);
            break;
    }
    return ESP_OK;
}

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
    mqtt_event_handler_cb(event_data);
}

static void mqtt_app_start(void)
{
	led_set(2, "ffff00",0);
    esp_mqtt_client_config_t mqtt_cfg = {
        .uri = CONFIG_BROKER_URL,
		//last will, use to indicate device state
		.lwt_topic = pub_topic_status,
		.lwt_msg = "offline",
		.lwt_msg_len = sizeof("offline")-1,
		.lwt_qos = 1,
		.lwt_retain = 1,
		.keepalive = 5
    };
#if CONFIG_BROKER_URL_FROM_STDIN
    char line[128];

    if (strcmp(mqtt_cfg.uri, "FROM_STDIN") == 0) {
        int count = 0;
        printf("Please enter url of mqtt broker\n");
        while (count < 128) {
            int c = fgetc(stdin);
            if (c == '\n') {
                line[count] = '\0';
                break;
            } else if (c > 0 && c < 127) {
                line[count] = c;
                ++count;
            }
            vTaskDelay(10 / portTICK_PERIOD_MS);
        }
        mqtt_cfg.uri = line;
        printf("Broker url: %s\n", line);
    } else {
        ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
        abort();
    }
#endif /* CONFIG_BROKER_URL_FROM_STDIN */

    client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
    esp_mqtt_client_start(client);
}

/**
 * @brief GPS Event Handler
 *
 * @param event_handler_arg handler specific arguments
 * @param event_base event base, here is fixed to ESP_NMEA_EVENT
 * @param event_id event id
 * @param event_data event specific arguments
 */
static void gps_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
    gps_t *gps = NULL;
    switch (event_id) {
    case GPS_UPDATE:
        gps = (gps_t *)event_data;
        /* print information parsed from GPS statements */
//        ESP_LOGI(TAG, "%d/%d/%d %d:%d:%d => \r\n"
//                "\t\t\t\t\t\tlatitude   = %.05f°N\r\n"
//                "\t\t\t\t\t\tlongitude = %.05f°E\r\n"
//                "\t\t\t\t\t\taltitude   = %.02fm\r\n"
//                "\t\t\t\t\t\tspeed      = %fm/s\r\n"
//        		"\t\t\t\t\t\tfixmode    = %d\r\n"
//				"\t\t\t\t\t\tfix        = %d\r\n",
//                 gps->date.year + YEAR_BASE, gps->date.month, gps->date.day,
//                 gps->tim.hour + TIME_ZONE, gps->tim.minute, gps->tim.second,
//                 gps->latitude, gps->longitude, gps->altitude, gps->speed, gps->fix_mode, gps->fix);
        static char buf[256];
        int len = snprintf(buf,sizeof(buf),
        		"%.05f,%.05f,%.02f,%f,%d,%d",
                 gps->latitude, gps->longitude, gps->altitude, gps->speed, gps->fix_mode, gps->fix);
        esp_mqtt_client_publish(client, pub_topic_rtk_location, buf, len, 0, 0);
        break;
    case GPS_UNKNOWN:
        /* print unknown statements */
        ESP_LOGW(TAG, "Unknown statement:%s", (char *)event_data);
        break;
    default:
        break;
    }
}
static void uwb_event_handler(void *event_handler_arg,esp_event_base_t event_base,int32_t event_id ,void *event_data)
{
	uwb_t *uwb = NULL;
	switch(event_id){
	case UWB_UPDATE:
		uwb = (uwb_t *)event_data;
		static char buf[256];
		int len = snprintf(buf,sizeof(buf),"%d,%d,%d,%d",uwb->pos.x,uwb->pos.y,uwb->pos.z,uwb->pos.qf);
		esp_mqtt_client_publish(client,pub_topic_uwb_location,buf,len,0,0);
		break;
	case UWB_NOT_UPDATE:
		esp_mqtt_client_publish(client,pub_topic_uwb_location,"Location data is not updated",0,0,0);
		ESP_LOGW(TAG,"Location data is not updated");
		break;
	default:
		break;
	}
}
void app_main(void)
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
    esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);

    topic_fill_device_id();
    hmi_init();
    console_init();

    ESP_ERROR_CHECK(wifi_init_sta("yinjunlin","yinjunlin521"));

    mqtt_app_start();
    /* NMEA parser configuration */
    rtk_config_t config = NMEA_PARSER_CONFIG_DEFAULT();
    /* init NMEA parser library */
    rtk_hdl = rtk_init(&config);
    /* register event handler for NMEA parser library */
    rtk_add_handler(rtk_hdl, gps_event_handler, NULL);









    uwb_config_t config_uwb = UWB_CONFIG_DEFALT();
    uwb_hdl = uwb_init(&config_uwb);
    uwb_add_handler(uwb_hdl,uwb_event_handler,NULL);
    keys_init();




    //OTA
    user_mqtt_app_start();
  	//OTA

}
